package com.lianboke.link.ad.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by admin on 2017/9/13.
 */

public class SystemUtils {

    private final static int kSystemRootStateUnknow=-1;
    private final static int kSystemRootStateDisable=0;
    private final static int kSystemRootStateEnable=1;
    private static int systemRootState=kSystemRootStateUnknow;


    /**
     * 是否root
     * @return
     */
    public static boolean isRootSystem()
    {
//        if(systemRootState==kSystemRootStateEnable)
//        {
//            return true;
//        }
//        else if(systemRootState==kSystemRootStateDisable)
//        {
//
//            return false;
//        }
        File f=null;
        final String kSuSearchPaths[]={"/system/bin/","/system/xbin/","/system/sbin/","/sbin/","/vendor/bin/"};
        try{
            for(int i=0;i<kSuSearchPaths.length;i++)
            {
                f=new File(kSuSearchPaths[i]+"su");
                if(f!=null&&f.exists())
                {
                    systemRootState=kSystemRootStateEnable;
                    return true;
                }
            }
        }catch(Exception e)
        {
        }
        systemRootState=kSystemRootStateDisable;
        return false;
    }


    /**
     * 获取ip 地址
     * @return
     */
    public static String getLocalIpAddress()
    {
        try
        {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
            {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
                {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress())
                    {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        }
        catch (SocketException ex)
        {
        }
        return null;
    }

    /**
     * 申请root权限
     * @param command
     * @return
     */
//    public static boolean phoneRootCommand(String command){
//        Process process = null;
//        DataOutputStream os = null;
//        try{
//            process = Runtime.getRuntime().exec("su");
//            os = new DataOutputStream(process.getOutputStream());
//            os.writeBytes(command + "\n");
//            os.writeBytes("exit\n");
//            os.flush();
//            int exitValue = process.waitFor();
//            KLog.e("phone_root","--------exitValue---------------:"+exitValue);
//            if (exitValue == 0){
//                return true;
//            } else{
//                return false;
//            }
//        } catch (Exception e){
//            KLog.e("phone_root","--------Exception---------------:"+e.getMessage());
//            return false;
//        } finally{
//            try{
//                if (os != null){
//                    os.close();
//                }
//                process.destroy();
//            } catch (Exception e){
//            }
//        }
//    }

    public static boolean phoneRootCommand(String command){
        if(TextUtils.isEmpty(command)){
            return false;
        }
        Process process = null;
        DataOutputStream os = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = null;
        StringBuilder errorMsg = null;
        try {
            //静默安装需要root权限
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.write(command.getBytes());
            os.writeBytes("\n");
            os.writeBytes("exit\n");
            os.flush();
            //执行命令
            process.waitFor();
            //获取返回结果
            successMsg = new StringBuilder();
            errorMsg = new StringBuilder();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s =successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine())!= null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (process != null) {
                    process.destroy();
                }
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(TextUtils.isEmpty(errorMsg.toString().trim()) && TextUtils.isEmpty(successMsg.toString().trim())){
            return true;
        }else if(TextUtils.isEmpty(errorMsg.toString().trim()) && !TextUtils.isEmpty(successMsg.toString().trim())){
            return true;
        }else if(!TextUtils.isEmpty(errorMsg.toString().trim()) ){
            return false;
        }else {
            return false;
        }
    }

    /**
     * 静默安装
     */
    public static  boolean installApkSlient( String strApkPath) {
        if(TextUtils.isEmpty(strApkPath)){
            return false;
        }
        //String cmd = "pm install -r/mnt/sdcard/test.apk";
        String cmd = "pm install -r "+strApkPath;
        Process process = null;
        DataOutputStream os = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = null;
        StringBuilder errorMsg = null;
        try {
            //静默安装需要root权限
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.write(cmd.getBytes());
            os.writeBytes("\n");
            os.writeBytes("exit\n");
            os.flush();
            //执行命令
            process.waitFor();
            //获取返回结果
            successMsg = new StringBuilder();
            errorMsg = new StringBuilder();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s =successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine())!= null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (process != null) {
                    process.destroy();
                }
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(TextUtils.isEmpty(errorMsg.toString().trim()) && TextUtils.isEmpty(successMsg.toString().trim())){
            return true;
        }else if(TextUtils.isEmpty(errorMsg.toString().trim()) && !TextUtils.isEmpty(successMsg.toString().trim())){
            return true;
        }else if(!TextUtils.isEmpty(errorMsg.toString().trim()) ){
            return false;
        }else {
            return false;
        }
    }

    /**
     * 静默卸载任务
     */
    public static boolean uninstallApkSlient(String strPackageName) {
        if(TextUtils.isEmpty(strPackageName)){
            return false;
        }
        String cmd = "pm uninstall "+ strPackageName;
        Process process = null;
        DataOutputStream os = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = null;
        StringBuilder errorMsg = null;
        try {
            //卸载也需要root权限
            process =Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.write(cmd.getBytes());
            os.writeBytes("\n");
            os.writeBytes("exit\n");
            os.flush();
            //执行命令
            process.waitFor();
            //获取返回结果
            successMsg = new StringBuilder();
            errorMsg = new StringBuilder();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s =successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine())!= null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (process != null) {
                    process.destroy();
                }
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(TextUtils.isEmpty(errorMsg.toString().trim()) && TextUtils.isEmpty(successMsg.toString().trim())){
            return true;
        }else if(TextUtils.isEmpty(errorMsg.toString().trim()) && !TextUtils.isEmpty(successMsg.toString().trim())){
            return true;
        }else if(!TextUtils.isEmpty(errorMsg.toString().trim()) ){
            return false;
        }else {
            return false;
        }
    }

    /**
     * 手动安装
     * @param actContext
     * @param fileName
     */
    public static void installApkHand(Context actContext, String fileName) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.parse("file://" + fileName),"application/vnd.android.package-archive");
        actContext.startActivity(intent);
    }

    /**
     *
     * 手动卸载
     * @param actContext
     * @param packageName
     */
    public static void uninstallApkHand(Context actContext, String packageName) {
        Uri uri = Uri.parse("package:" + packageName);
        Intent intent = new Intent(Intent.ACTION_DELETE, uri);
        actContext.startActivity(intent);
    }
}
